<?php
/**
 * 加油站点表
 * Created by PhpStorm.
 * User: LRChang
 * Date: 2018/5/30
 * Time: 14: 26
 * Mail: hjklrchang@qq.com
 */

namespace app\adminapi\model;

use app\adminapi\filter\OilStationFilter;
use app\base\exception\RecordNotFoundException;
use traits\model\SoftDelete;

class OilStation extends  Common {
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    /**
     * 获取加油站点列表
     * @param $where
     * @param $fields
     * @param int $page
     * @param int $pagenum
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function listData($where, $fields, $page = 1, $pagenum = 20) {
        $filter = new OilStationFilter($fields, $where);
        $condition = $filter->geFiltered();
        $where = $condition['where'];
        $fields = $condition['field'];
        $mark = $filter->getMark();

        $buildQuery = function($query) use ($where) {
            self::authCompanyQuery($query, $where, 'company_id');
        };

        $result = [];
        $result['count'] = $this->where($buildQuery)->count();
        $result['list'] = $this->where($buildQuery)
            ->page($page, $pagenum)
            ->field($fields)
            ->order('oil_station_id desc')
            ->select();

        return array_merge($result, $mark);
    }

    /**
     * 新增或者编辑加油站点
     * @param $params
     * @return $this|false|int
     * @throws RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function createOrUpdate($params) {
        $session = (new User())->getLoginUser();
        if(isset($params['oil_station_id'])) {
            $where = ['oil_station_id' => $params['oil_station_id']];
            $buildQuery = function($query) use ($where) {
                self::authCompanyQuery($query, $where, 'company_id');
            };

            $oil_station = self::get($buildQuery);
            if(!$oil_station) {
                throw new RecordNotFoundException();
            }
        }elseif(!self::isSuperAdmin($session) && $session['user']['company_id']) {
            $params['company_id'] = $session['user']['company_id'];
        }

        // 验证单位是否存在
        $this->addRelativeFields( $params, 'app\adminapi\model\Company', $params['company_id'],  [], '关联单位不存在');

        if(isset($params['oil_station_id'])) {
            return $this->isUpdate(true)->save($params);
        }

        $this->data($params)->save();
        return $this;
    }
}